/**
 * 配置管理器 - 负责弹幕配置的管理和验证
 */
import type { BarrageConfig } from '../../types'

/**
 * 默认配置常量
 */
export const DEFAULT_CONFIG: Required<BarrageConfig> = {
  opacity: 0.9,
  speed: 200,
  fontSize: 20,
  trackCount: 8,
  trackHeight: 50,
  maxBarrages: 6,
  interval: 2000,
  collision: true,
  faceDetection: false,
  debug: false,
  showSkeleton: true,
  minBarrageGap: 20,
  className: '',
  style: {},
  avoidOverlap: true,
  minSpace: 10,
  maxDisplayCount: 50,
  trackFillMode: 'normal',
  // 🆕 新增高级设置功能
  density: 'normal',
  scaleWithScreen: false,
  preventSubtitleBlock: false,
  displayRegion: 1.0
}

/**
 * 配置管理器类
 */
export class ConfigManager {
  private config: Required<BarrageConfig>

  constructor(initialConfig?: Partial<BarrageConfig>) {
    this.config = this.mergeConfig(initialConfig)
  }

  /**
   * 合并配置
   */
  private mergeConfig(customConfig?: Partial<BarrageConfig>): Required<BarrageConfig> {
    return {
      ...DEFAULT_CONFIG,
      ...customConfig
    }
  }

  /**
   * 获取当前配置
   */
  getConfig(): Required<BarrageConfig> {
    return this.config
  }

  /**
   * 更新配置
   */
  updateConfig(newConfig: Partial<BarrageConfig>): Required<BarrageConfig> {
    this.config = {
      ...this.config,
      ...newConfig
    }
    return this.config
  }

  /**
   * 获取单个配置项
   */
  get<K extends keyof BarrageConfig>(key: K): Required<BarrageConfig>[K] {
    return this.config[key]
  }

  /**
   * 设置单个配置项
   */
  set<K extends keyof BarrageConfig>(key: K, value: Required<BarrageConfig>[K]): void {
    this.config[key] = value
  }

  /**
   * 验证配置合法性
   */
  validateConfig(config: Partial<BarrageConfig>): { valid: boolean; errors: string[] } {
    const errors: string[] = []

    if (config.opacity !== undefined && (config.opacity < 0 || config.opacity > 1)) {
      errors.push('opacity 必须在 0-1 之间')
    }

    if (config.speed !== undefined && config.speed <= 0) {
      errors.push('speed 必须大于 0')
    }

    if (config.fontSize !== undefined && config.fontSize <= 0) {
      errors.push('fontSize 必须大于 0')
    }

    if (config.trackCount !== undefined && config.trackCount <= 0) {
      errors.push('trackCount 必须大于 0')
    }

    if (config.maxBarrages !== undefined && config.maxBarrages <= 0) {
      errors.push('maxBarrages 必须大于 0')
    }

    return {
      valid: errors.length === 0,
      errors
    }
  }

  /**
   * 重置为默认配置
   */
  reset(): Required<BarrageConfig> {
    this.config = { ...DEFAULT_CONFIG }
    return this.config
  }
}

